package cn.zswltech.gruul.web.api.util;

import cn.zswltech.gruul.common.util.MD5Util;
import cn.zswltech.gruul.common.util.StringUtil;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by zhongjianwei on 2018/9/10.
 */
public class CookieUtils {
    public static final String WL_TOKEN = "_qjt_ac_";

    public static final String WL_SALT = "_salt_";

    public static final String HEADER_NAME = "token";

    public static final String OA_SECRET = "secret";

    public static final String OA_TIMESTAMP = "timestamp";

    public static final String OA_RANDOM = "random";

    public static final String MENU_ID = "menuId";

    public static final String SYSTEM_CODE = "System-Code";

    /**
     * 单位是秒,cookie有效期1天
     */
    public static final int COOKIE_TOKEN_EXPIRE_TIME = 24 * 3600;

    /**
     * 返回name为"_td_token_"的cookie值
     *
     * @param request
     * @return
     */
    public static String getWlToken(HttpServletRequest request) {
        return getCookieValByName(request, WL_TOKEN);
    }

//    /**
//     * 设置wlToken
//     */
//    public static void setWlToken(HttpServletResponse response, String wlToken) {
//        Cookie cookie = new Cookie(WL_TOKEN, wlToken);
//        cookie.setMaxAge(COOKIE_TOKEN_EXPIRE_TIME);
//        cookie.setPath("/");
//        cookie.setHttpOnly(true);
//        response.addCookie(cookie);
//    }
    /**
     * 返回name为"menuId"的header值
     *
     * @param request
     * @return
     */
    public static Long getMenuId(HttpServletRequest request) {
        try {
            String menuId =  request.getHeader(MENU_ID);
            return Long.valueOf(menuId);
        }catch (Exception e){
        }
        return null;
    }

    /**
     *
     * @param request
     * @return
     */
    public static String getLoginSalt(HttpServletRequest request) {
        return getCookieValByName(request, WL_SALT);
    }

//    /**
//     * 删除name为"_td_token_"的cookie值
//     *
//     * @param response
//     * @return
//     */
//    public static void deleteWlToken(HttpServletResponse response) {
//        Cookie cookie = new Cookie(WL_TOKEN, null);
//        cookie.setMaxAge(0); // 立即删除型
//        cookie.setPath("/"); // 项目所有目录均有效，这句很关键，否则不敢保证删除
//        cookie.setHttpOnly(true);
//        response.addCookie(cookie); // 重新写入，将覆盖之前的
//    }

//    /**
//     * 根据cookie的name返回cookie
//     *
//     * @param request
//     * @param name    cookiename
//     * @return
//     */
//    public static Cookie getCookieByName(HttpServletRequest request, String name) {
//        Cookie c = null;
//        if (request == null) {
//            return null;
//        }
//        Cookie[] cookies = request.getCookies();
//        if (cookies != null && (null != name && !"".equals(name.trim()))) {
//            for (Cookie cookie : cookies) {
//                String cookieName = cookie.getName();
//                if (name.equals(cookieName)) {
//                    c = cookie;
//                    break;
//                }
//            }
//        }
//        return c;
//    }

    /**
     * 根据cookiename返回cookieval
     *
     * @param request
     * @param name
     * @return
     */
    public static String getCookieValByName(HttpServletRequest request, String name) {
        String result = null;
//        Cookie cookie = getCookieByName(request, name);
//        if (cookie != null) {
//            result = cookie.getValue();
//        }
        String header = request.getHeader(HEADER_NAME);
        JSONObject jsonObject = JSONObject.parseObject(header);
        if (jsonObject == null){
            return null;
        }
        result = jsonObject.getString(name);
        return result;
    }

    /**
     * 校验CSRF Token
     *
     * @param request
     * @return
     */
    public static boolean checkCSRFToken(HttpServletRequest request) {
        String csrfToken = request.getHeader("X-Cf-Random");
        String wlToken = getWlToken(request);
        if (StringUtil.isBlank(wlToken)) {
            return false;
        }
        if (StringUtil.isBlank(csrfToken) || csrfToken.length() != 36) {
            return false;
        }
        int index1 = Integer.parseInt(csrfToken.substring(0, 1));
        int index2 = Integer.parseInt(csrfToken.substring(1, 2));
        int index3 = Integer.parseInt(csrfToken.substring(34, 35));
        int index4 = Integer.parseInt(csrfToken.substring(35, 36));
        String md5 = MD5Util.MD5(wlToken.substring(index1, index1 + 1) + wlToken.substring(index2, index2 + 1) + wlToken.substring(index3, index3 + 1) + wlToken.substring(index4, index4 + 1));
        if (md5.equalsIgnoreCase(csrfToken.substring(2, 34))) {
            return true;
        }
        return false;
    }

    public static void setCookieValByName(HttpServletResponse response,String cookieName, String cookieValue) {
        Cookie cookie = new Cookie(cookieName,cookieValue);
        //cookie.setMaxAge(COOKIE_TOKEN_EXPIRE_TIME);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    public static String getSJToken(HttpServletRequest request) {
        return request.getHeader("token");
    }
}
